package leetcodev1.树;

import leetcodev1.链表.Solution;

import java.util.Stack;

public class LeetCode98 {
    //不止要和父节点比较，还要从根节点开始比较
    //不应该直接和子树比较，而是应该用子节点和父节点比较
    public boolean isValidBST1(TreeNode root) {
        if (root == null) {
            return true;
        }

        if (root.left == null && root.right == null) {
            return true;
        }

        if (root.left != null && root.right == null) {
            return root.val > root.left.val && isValidBST1(root.left);
        }

        if (root.left == null && root.right != null) {
            return root.val < root.right.val && isValidBST1(root.right);
        }

        return root.val > root.left.val && root.val < root.right.val && isValidBST1(root.left) && isValidBST1(root.right);
    }

    //中序遍历的二叉树是有序（记住）
    //先写出非递归的中序遍历
    public boolean isValidBST(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode curr = root;
        double preValue = -Double.MAX_VALUE;

        while (!stack.isEmpty() || curr != null) {
            while (curr != null) {
                stack.push(curr);
                curr = curr.left;
            }

            TreeNode pop = stack.pop();
            if (pop.val <= preValue) {
                return false;
            }
            preValue = pop.val;
            curr = pop.right;
        }

        return true;
    }
}

class Answer98 {
    //1.递归
    public boolean isValidBST(TreeNode root) {
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    //只比较大小 不必关心
    public boolean isValidBST(TreeNode node, long lower, long upper) {
        if (node == null) {
            return true;
        }
        if (node.val <= lower || node.val >= upper) {
            return false;
        }
        return isValidBST(node.left, lower, node.val) && isValidBST(node.right, node.val, upper);
    }

    //2.中序遍历
    //参考上面
}
